<template>
  <div>
    <div class="dept-tree">
      <div class="dept-left">
        <div class="dept-content">
          <el-input v-model="filterText" placeholder="输入关键字进行过滤" class="dept-tree-input" />
          <div class="dept-button">
            <el-row>
              <el-button type="primary" size="medium " plain @click="addDept">部门新增</el-button>
              <el-button type="warning" size="medium " plain @click="editDept">部门编辑</el-button>
            </el-row>
          </div>
          <div class="block">
            <el-tree
              ref="tree"
              :data="deptTreeArray"
              node-key="id"
              :expand-on-click-node="false"
              default-expand-all
              :filter-node-method="filterNode"
              :highlight-current="true"
              @node-click="getCurrentKey()"
            />
          </div>
        </div>
      </div>
      <div class="dept-right">
        <div v-show="deptInfoShow()" class="dept-detail dept-common">
          <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
            <div class="imput-buttom">
              <el-form-item label="部门名称:" class="name" prop="sysDeptName">
                <el-input v-model="ruleForm.sysDeptName" class="input" :disabled="isDisabled()" placeholder="请输入内容" autocomplete="off" />
              </el-form-item>
            </div>
            <div class="imput-buttom">
              <el-form-item label="父部门名称:" class="name">
                <el-select v-model="ruleForm.fatherDeptName" class="input" :disabled="parentIdIsDisabled()" placeholder="请输入内容" @change="selectDeptChange">
                  <el-option
                    v-for="item of fatherDeptList"
                    v-if="fatherDeptList && fatherDeptList.length >0"
                    :key="item.sysDeptUuid"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="imput-buttom">
              <el-form-item label="父部门id:" class="name" prop="sysDeptParentId">
                <el-input v-model="ruleForm.sysDeptParentId" class="input" :disabled="true" placeholder="请输入内容" />
              </el-form-item>
            </div>
            <div class="imput-buttom">
              <el-form-item label="排序:" class="name" prop="sysDeptSeq">
                <el-input v-model="ruleForm.sysDeptSeq" class="input" :disabled="isDisabled()" placeholder="请输入内容" autocomplete="off" />
              </el-form-item>
            </div>
            <div class="imput-buttom">
              <el-form-item label="状态:" prop="sysDeptStatus">
                <el-radio v-model="ruleForm.sysDeptStatus" class="input radio" :disabled="isDisabled()" label="0" border size="medium">启用</el-radio>
                <el-radio v-model="ruleForm.sysDeptStatus" class="input radio" :disabled="isDisabled()" label="1" border size="medium">禁用</el-radio>
              </el-form-item>
            </div>
            <div class="imput-buttom imput-area">
              <el-form-item label="备注:" prop="sysDeptRemark">
                <el-input v-model="ruleForm.sysDeptRemark" class="input" :disabled="isDisabled()" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入备注" />
              </el-form-item>
            </div>
            <el-form-item class="submit">
              <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Dept from '@/api/axios/api/author/dept'
import Tip from '@/utils/tip'

export default {
  name: 'AuthDept',
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('排序大小不能为空'))
      }
      if (!Number.isInteger(Number(value))) {
        callback(new Error('请输入数字'))
      }
      callback()
    }
    return {
      filterText: '',
      deptTreeArray: [],
      node: {},
      data: [],
      // 父部门名称的下拉框集合
      fatherDeptList: [],
      // 所有部门集合 k 主键 v 对象
      allDeptMap: new Map(),
      // 一棵树的首级
      firstDeptTree: {},
      // 表单提交类型 ''什么事也不做  '1'新增 '2'编辑
      deptSubmitType: '',
      // 暂时用不到
      deptInfoShowBoolean: true,
      // 表单是否禁用
      isDisabledBoolean: false,
      // 父部门名称 是否禁用
      parentIdIsDisabledBoolean: false,
      ruleForm: {
        groupId: null,
        id: null,
        sysDeptParentId: null,
        fatherDeptName: '',
        sysDeptName: '',
        sysDeptRemark: '',
        sysDeptSeq: null,
        sysDeptUuid: '',
        sysDeptStatus: '1'
      },
      rules: {
        sysDeptName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        sysDeptSeq: [
          { required: true, validator: checkAge, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(this.$refs.tree.getCheckedKeys())
    }
  },
  created() {
    this.deptTreeData()
  },
  methods: {
    deptInfoShow() {
      return this.deptInfoShowBoolean
    },
    isDisabled() {
      return this.isDisabledBoolean
    },
    parentIdIsDisabled() {
      return this.parentIdIsDisabledBoolean
    },
    submitForm(formName) {
      if (this.deptSubmitType === '') {
        return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 新增
          if (this.deptSubmitType === '1') {
            Dept.deptAdd(this.ruleForm).then(res => {
              if (res.status === 200) {
                Tip.success(res.data)
                this.deptTreeData()
              } else {
                Tip.error(res.data)
              }
            })
          } else if (this.deptSubmitType === '2') { // 编辑部门
            Dept.deptEdit(this.ruleForm).then(res => {
              if (res.status === 200) {
                Tip.success(res.data)
                this.deptTreeData()
              } else {
                Tip.error(res.data)
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    addDept() {
      this.resetForm('ruleForm')
      this.fatherDeptList = []
      // 新增部门
      this.deptSubmitType = '1'
      const currentDept = this.$refs.tree.getCurrentNode()
      this.parentIdIsDisabledBoolean = true
      this.isDisabledBoolean = false
      if (currentDept === null) {
        this.ruleForm.sysDeptParentId = this.firstDeptTree.id
        this.ruleForm.fatherDeptName = this.firstDeptTree.sysDeptName
      } else {
        this.ruleForm.sysDeptParentId = currentDept.id
        this.ruleForm.fatherDeptName = currentDept.label
        this.fatherDeptList.push(this.ruleForm)
      }
    },
    editDept() {
      this.resetForm('ruleForm')
      // 编辑部门
      this.deptSubmitType = '2'
      const currentDept = this.$refs.tree.getCurrentNode()
      if (currentDept === null) {
        Tip.warnin('请选择部门')
      } else {
        Dept.deptDetail(currentDept).then(res => {
          this.parentIdIsDisabledBoolean = false
          this.isDisabledBoolean = false
          this.ruleForm.id = res.id
          this.ruleForm.groupId = res.groupId
          this.ruleForm.sysDeptParentId = res.sysDeptParentId
          this.ruleForm.sysDeptName = res.sysDeptName
          this.ruleForm.sysDeptSeq = res.sysDeptSeq
          this.ruleForm.sysDeptUuid = res.sysDeptUuid
          this.ruleForm.sysDeptStatus = res.sysDeptStatus
          this.ruleForm.sysDeptRemark = res.sysDeptRemark
          const currentDept = this.$refs.tree.data
          const currentDeptJson = JSON.parse(JSON.stringify(currentDept))
          this.fatherDeptList = []
          this.recursiveRenderDeptSelect(currentDeptJson, 1, res.id, res.sysDeptLevel)
        })
      }
    },
    getCurrentKey() {
      this.resetForm('ruleForm')
      this.deptSubmitType = ''
      const currentDept = this.$refs.tree.getCurrentNode()
      this.ruleForm.groupId = currentDept.groupId
      this.ruleForm.sysDeptParentId = currentDept.sysDeptParentId
      this.ruleForm.id = currentDept.id
      this.ruleForm.sysDeptName = currentDept.label
      this.ruleForm.sysDeptRemark = currentDept.sysDeptRemark
      this.ruleForm.sysDeptUuid = currentDept.sysDeptUuid
      this.ruleForm.sysDeptSeq = currentDept.sysDeptSeq
      this.ruleForm.sysDeptStatus = currentDept.sysDeptStatus
      this.isDisabledBoolean = true
      this.parentIdIsDisabledBoolean = true
      const deptObj = this.allDeptMap.get(currentDept.sysDeptParentId)
      this.ruleForm.fatherDeptName = deptObj === undefined ? '' : deptObj.sysDeptName
    },
    selectDeptChange(value) {
      this.ruleForm.sysDeptParentId = value
    },
    recursiveRenderDeptSelect(deptList, level, id, deptLevel) {
      level = level | 0
      if (deptList && deptList.length > 0) {
        deptList.forEach(dept => {
          var blank = ''
          if (level > 1) {
            for (var j = 3; j <= level; j++) {
              blank += '...'
            }
            blank += '∟'
          }
          if (id !== dept.id && dept.sysDeptLevel.indexOf(deptLevel) === -1) {
            dept.label = blank + dept.label
            this.fatherDeptList.push(dept)
          }
          if (dept.children && dept.children.length > 0) {
            this.recursiveRenderDeptSelect(dept.children, level + 1, id, deptLevel)
          }
        })
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    deptToTree(res) {
      // 建立个树形结构,需要定义个最顶层的父节点renderContent
      const parent = []
      if (res && res.length > 0) {
        res.forEach(dept => {
          const obj = {
            label: dept.sysDeptName,
            id: dept.id,
            sysDeptUuid: dept.sysDeptUuid,
            sysDeptRemark: dept.sysDeptRemark,
            sysDeptParentId: dept.sysDeptParentId,
            sysDeptLevel: dept.sysDeptLevel,
            sysDeptSeq: dept.sysDeptSeq,
            groupId: dept.groupId,
            sysDeptStatus: dept.sysDeptStatus,
            children: this.childDeptTree(dept.deptList)
          }
          this.allDeptMap.set(dept.id, dept)
          this.firstDeptTree = dept
          // 数组加数组值
          parent.push(obj)
        })
      }
      this.deptTreeArray = parent
    },
    childDeptTree(childDeptArray) {
      const child = []
      if (childDeptArray && childDeptArray.length > 0) {
        childDeptArray.forEach(dept => {
          const obj = {
            label: dept.sysDeptName,
            id: dept.id,
            sysDeptUuid: dept.sysDeptUuid,
            sysDeptRemark: dept.sysDeptRemark,
            sysDeptParentId: dept.sysDeptParentId,
            sysDeptLevel: dept.sysDeptLevel,
            sysDeptSeq: dept.sysDeptSeq,
            groupId: dept.groupId,
            sysDeptStatus: dept.sysDeptStatus,
            children: this.childDeptTree(dept.deptList)
          }
          this.allDeptMap.set(dept.id, dept)
          child.push(obj)
        })
      }
      return child
    },
    deptTreeData() {
      Dept.deptTree().then(res => {
        this.deptToTree(res.data)
      })
    },
    deptDetail(data) {
    },
    renderContent(h, { node, data, store }) {
      return ('')
    }
  }
}
</script>

<style lang="stylus" scoped>
  .dept-tree
    margin-left 150px
    padding-top 10px
    overflow hidden
    display flex
    overflow hidden
    .dept-left
      width 30%
      overflow hidden
      .dept-content
        width 300px
        overflow hidden
        .dept-button
          margin-top 10px
          margin-bottom 10px
    .dept-right
      width 70%
      overflow hidden
      .dept-common
        margin 30px 10%
        .imput-buttom
          margin-bottom 10px
          .input
            width 70%
          .radio
            width 31%
          .namea
            background-color red
            text-align center
            width 100px
            white-space: nowrap;
            display inline-block
            border-top-right-radius: 0
            border: 1px solid #DCDFE6
            border-bottom-right-radius: 0
            background-color: #f5f7fa;
            color: #909399;
            border-radius: 4px;
            vertical-align: middle;
        .imput-area
          margin-bottom 20px
</style>
